﻿using System;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace WEIShareWCFRole.BaseCode
{
    /// <summary>
    /// Helpers Classes and Methods
    /// </summary>
    public class Helpers
    {
        #region ToInt(string, int)
        /// <summary>
        /// Converts a string to int or the specified default value if can't convert
        /// </summary>
        /// <param name="toConvert"></param>
        /// <returns></returns>
        public static int ToInt(string toConvert, int defaultValue)
        {
            if (!string.IsNullOrEmpty(toConvert))
            {
                int tempValue = 0;
                if (int.TryParse(toConvert, out tempValue))
                {
                    return tempValue;
                }
            }

            return defaultValue;
        }
        #endregion


        #region ToString(decimal?...)
        /// <summary>
        /// Converts a decimal to a formatted string
        /// </summary>
        /// <param name="toConvert"></param>
        /// <returns></returns>
        public static string ToString(decimal? toConvert, string formatToUse)
        {
            if (toConvert.HasValue)
                return toConvert.Value.ToString(formatToUse);

            return string.Empty;
        }

        /// <summary>
        /// Converts a decimal to a formatted string
        /// </summary>
        /// <param name="toConvert"></param>
        /// <returns></returns>
        public static string ToString(decimal? toConvert)
        {
            return ToString(toConvert, string.Empty);
        }
        #endregion


        #region ToString(bool?...)
        /// <summary>
        /// Converts a bool to a formatted string
        /// </summary>
        public static string ToString(bool? toConvert)
        {
            return ToString(toConvert, null);
        }

        public static string ToString(bool? toConvert, bool? defaultValue)
        {
            if (toConvert.HasValue)
                return toConvert.Value.ToString();

            if (defaultValue.HasValue)
                return defaultValue.ToString();
            else
                return string.Empty;
        }
        #endregion


        #region ToString(int?...)
        /// <summary>
        /// Converts a int to a formatted string
        /// </summary>
        public static string ToString(int? toConvert)
        {
            return ToString(toConvert, String.Empty);
        }

        public static string ToString(int? toConvert, string formatToUse)
        {
            return ToString(toConvert, formatToUse, String.Empty);
        }

        public static string ToString(int? toConvert, string formatToUse, string defaultValue)
        {
            if (toConvert.HasValue)
                return toConvert.Value.ToString(formatToUse);

            return defaultValue;
        }
        #endregion


        #region ToString(long?...)
        /// <summary>
        /// Converts a long to a formatted string
        /// </summary>
        public static string ToString(long? toConvert)
        {
            return ToString(toConvert, String.Empty);
        }

        public static string ToString(long? toConvert, string formatToUse)
        {
            return ToString(toConvert, formatToUse, String.Empty);
        }

        public static string ToString(long? toConvert, string formatToUse, string defaultValue)
        {
            if (toConvert.HasValue)
                return toConvert.Value.ToString(formatToUse);

            return defaultValue;
        }
        #endregion


        /// <summary>
        /// Remove from the ASP.NET cache all items whose key starts with the input prefix
        /// </summary>
        public static void PurgeCacheItems(string keyPrefix)
        {
            if (HttpRuntime.Cache == null)
                return;

            foreach (DictionaryEntry cacheItem in HttpRuntime.Cache)
            {
                if (cacheItem.Key.ToString().StartsWith(keyPrefix, StringComparison.OrdinalIgnoreCase))
                    HttpRuntime.Cache.Remove(cacheItem.Key.ToString());
            }

        }

        /// <summary>
        /// Class used for encryption and decryption purposes
        /// </summary>
        public class Cryptor
        {

            static string passPhrase = ""; // can be any string
            static string saltValue = "";  // can be any string
            static int passwordIterations = 1; // can be any number
            static string initVector = ""; // must be 16 bytes (Characters)

            /// <summary>
            /// Encrypts a string
            /// </summary>
            /// <param name="input">String to be encrypted</param>
            /// <returns>Encrypted string</returns>
            public static string Encrypt(string input)
            {

                // Test data
                string data = input;
                byte[] utfdata = UTF8Encoding.UTF8.GetBytes(data);
                byte[] saltBytes = UTF8Encoding.UTF8.GetBytes(saltValue);

                // Our symmetric encryption algorithm
                AesManaged aes = new AesManaged();

                // We're using the PBKDF2 standard for password-based key generation
                Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, saltBytes, passwordIterations);

                // Setting our parameters
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;

                byte[] passwordBytes = password.GetBytes(aes.KeySize / 8);
                byte[] initVectorBytes = UTF8Encoding.UTF8.GetBytes(initVector);

                aes.Key = passwordBytes;
                aes.IV = initVectorBytes;

                // Encryption
                ICryptoTransform encryptTransf = aes.CreateEncryptor();

                // Output stream, can be also a FileStream
                MemoryStream encryptStream = new MemoryStream();
                CryptoStream encryptor = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);

                encryptor.Write(utfdata, 0, utfdata.Length);
                encryptor.Flush();
                encryptor.Close();

                // Showing our encrypted content
                byte[] encryptBytes = encryptStream.ToArray();

                string encryptedString = Convert.ToBase64String(encryptBytes);

                return encryptedString;

            }

            /// <summary>
            /// Decrypts a string
            /// </summary>
            /// <param name="base64Input">String to be decrypted</param>
            /// <returns>Decrypted string</returns>
            public static string Decrypt(string base64Input)
            {
                //byte[] encryptBytes = UTF8Encoding.UTF8.GetBytes(input);
                byte[] encryptBytes = Convert.FromBase64String(base64Input);
                byte[] saltBytes = Encoding.UTF8.GetBytes(saltValue);

                // Our symmetric encryption algorithm
                AesManaged aes = new AesManaged();

                // We're using the PBKDF2 standard for password-based key generation
                Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, saltBytes, passwordIterations);

                // Setting our parameters
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;

                byte[] passwordBytes = password.GetBytes(aes.KeySize / 8);
                byte[] initVectorBytes = UTF8Encoding.UTF8.GetBytes(initVector);

                aes.Key = passwordBytes;
                aes.IV = initVectorBytes;

                // Now, decryption
                ICryptoTransform decryptTrans = aes.CreateDecryptor();

                // Output stream, can be also a FileStream
                MemoryStream decryptStream = new MemoryStream();
                CryptoStream decryptor = new CryptoStream(decryptStream, decryptTrans, CryptoStreamMode.Write);

                decryptor.Write(encryptBytes, 0, encryptBytes.Length);
                decryptor.Flush();
                decryptor.Close();

                // Showing our decrypted content
                byte[] decryptBytes = decryptStream.ToArray();
                string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);

                return decryptedString;

            }
        }




    }
}